﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace Fcdbas.CodeBuilder
{
    /// <summary>
    /// FileHelper 用于简化与文件相关操作。
    /// </summary>
    public sealed class FileHelper
    {
        public FileHelper()
        {

        }

        #region GenerateFile 将字符串写成文件 －－ GenerateFile
        /// <summary>
        /// 将指定的字符串写入到指定的文件中
        /// </summary>
        /// <param name="file_path">文件路径</param>
        /// <param name="text">指定的字符串</param>
        /// <param name="extend_name">扩展名</param>
        public static void GenerateFile(string file_path, string text, string extend_name)
        {
            if (Path.GetExtension(file_path) != extend_name)
            {
                file_path += extend_name;
            }

            string directory_path = Path.GetDirectoryName(file_path);
            if (!Directory.Exists(directory_path))
            {
                Directory.CreateDirectory(directory_path);
            }

            FileStream fs = new FileStream(file_path, FileMode.Create, FileAccess.Write);

            StreamWriter sw = new StreamWriter(fs);

            sw.Write(text);
            sw.Flush();

            sw.Close();
            fs.Close();
        }
        /// <summary>
        /// 将指定的字符串写入到指定的文件中,当存在文件或者路径时会提问选择
        /// </summary>
        /// <param name="file_path">文件路径</param>
        /// <param name="text">指定的字符串</param>
        /// <param name="extend_name">扩展名</param>
        /// <returns >成功返回true，否则返回false</returns>
        public static bool GenerateFileEx(string file_path, string text, string extend_name)
        {
            if (Path.GetExtension(file_path) != extend_name)
            {
                file_path += extend_name;
            }

            if (File.Exists(file_path))
            {
                if (DialogResult.No == MessageBox.Show(string.Format("文件{0}已经存在 ！你想覆盖吗？", file_path), "提示", MessageBoxButtons.YesNo))
                {
                    return false;
                }
            }

            string directory_path = Path.GetDirectoryName(file_path);
            if (!Directory.Exists(directory_path))
            {
                if (DialogResult.No == MessageBox.Show(string.Format("目的文件夹不存在 ！你想创建吗？", directory_path), "提示", MessageBoxButtons.YesNo))
                {
                    return false;
                }

                Directory.CreateDirectory(directory_path);
            }

            try
            {
                FileStream fs = new FileStream(file_path, FileMode.Create, FileAccess.Write);

                StreamWriter sw = new StreamWriter(fs);

                sw.Write(text);
                sw.Flush();

                sw.Close();
                fs.Close();

                return true;
            }
            catch (Exception ee)
            {
                //return false ;
                throw ee;
            }
            //MessageBox.Show("成功生成代码文件" + file_path + " ！") ;
        }
        #endregion

        #region GetFileContent 读取文本文件
        /// <summary>
        /// 读取指定文本文件的内容
        /// </summary>
        /// <param name="file_path">文件的路径</param>
        /// <returns>读取的内容</returns>
        public static string GetFileContent(string file_path)
        {
            if (!File.Exists(file_path))
            {
                return null;
            }

            StreamReader reader = new StreamReader(file_path);
            string content = reader.ReadToEnd();
            reader.Close();

            return content;
        }
        #endregion

        #region WriteBuffToFile 将缓冲区的数据保存到文件中
        /// <summary>
        /// 将缓冲区的数据保存到文件中
        /// </summary>
        /// <param name="buff">缓冲区</param>
        /// <param name="offset">起始编移位置</param>
        /// <param name="lenToWrite">长度</param>
        /// <param name="file_path">要保存的文件路径</param>
        /// <param name="extend_name">扩展名</param>
        /// <param name="query_overwrite">是否询问覆盖</param>
        /// <returns>成功返回true，否则返回false</returns>
        public static bool WriteBuffToFile(byte[] buff, int offset, int lenToWrite, string file_path, string extend_name, bool query_overwrite)
        {
            if (Path.GetExtension(file_path) != extend_name)
            {
                file_path += extend_name;
            }

            if (query_overwrite)
            {
                if (File.Exists(file_path))
                {
                    if (DialogResult.No == MessageBox.Show(string.Format("文件{0}已经存在 ！你想覆盖吗？", file_path), "提示：", MessageBoxButtons.YesNo))
                    {
                        return false;
                    }
                }
            }

            string directory_path = Path.GetDirectoryName(file_path);
            if (!Directory.Exists(directory_path))
            {
                if (DialogResult.No == MessageBox.Show(string.Format("目的文件夹不存在 ！你想创建吗？", directory_path), "提示", MessageBoxButtons.YesNo))
                {
                    return false;
                }

                Directory.CreateDirectory(directory_path);
            }

            try
            {
                FileStream fs = new FileStream(file_path, FileMode.Create, FileAccess.Write);

                BinaryWriter bw = new BinaryWriter(fs);

                bw.Write(buff, offset, lenToWrite);
                bw.Flush();

                bw.Close();
                fs.Close();

                //MessageBox.Show("成功生成文件" + file_path + " ！") ;
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 将缓冲区的数据保存到文件中
        /// </summary>
        /// <param name="buff">缓冲区</param>
        /// <param name="file_path">要保存的文件路径</param>
        /// <param name="extend_name">扩展名</param>
        /// <param name="query_overwrite">是否询问覆盖</param>
        /// <returns>成功返回true，否则返回false</returns>
        public static bool WriteBuffToFile(byte[] buff, string file_path, string extend_name, bool query_overwrite)
        {
            return FileHelper.WriteBuffToFile(buff, 0, buff.Length, file_path, extend_name, query_overwrite);
        }
        #endregion

        #region ReadFileToBuff 将文件数据读到缓冲区中
        /// <summary>
        /// 将指定的文件内容读到指定的缓冲区
        /// </summary>
        /// <param name="file_path">文件路径</param>
        /// <param name="buff">缓冲区</param>
        /// <returns>成功返回true,否则返回false</returns>
        public static bool ReadFileToBuff(string file_path, out byte[] buff)
        {
            if (!File.Exists(file_path))
            {
                //MessageBox.Show(string.Format("失败，文件{0}不存在 ！" ,file_path)) ;
                buff = null;
                return false;
            }

            FileStream fs = new FileStream(file_path, FileMode.Open, FileAccess.Read);

            BinaryReader br = new BinaryReader(fs);

            buff = br.ReadBytes((int)fs.Length);

            br.Close();
            fs.Close();

            //MessageBox.Show("成功打开文件" + file_path + " ！") ;
            return true;
        }
        #endregion

        #region GetFileToOpen 得到需要打开（处理）的文件的路径
        /// <summary>
        /// 得到需要打开（处理）的文件的路径
        /// </summary>
        /// <param name="title">头名称</param>
        /// <returns>取得的路径</returns>
        public static string GetFileToOpen(string title)
        {
            OpenFileDialog openDlg = new OpenFileDialog();
            openDlg.Filter = "All Files (*.*)|*.*";
            openDlg.FileName = "";
            if (title != null)
            {
                openDlg.Title = title;
            }

            openDlg.CheckFileExists = true;
            openDlg.CheckPathExists = true;

            DialogResult res = openDlg.ShowDialog();
            if (res == DialogResult.OK)
            {
                return openDlg.FileName;
            }

            return null;
        }
        /// <summary>
        /// 得到需要打开（处理）的文件的路径
        /// </summary>
        /// <param name="title">头名称</param>
        /// <param name="extendName" >扩展名</param>
        /// <returns>取得的路径</returns>
        public static string GetFileToOpen(string title, string extendName)
        {
            OpenFileDialog openDlg = new OpenFileDialog();
            openDlg.Filter = string.Format("cfp Files (*{0})|*{0}", extendName);
            openDlg.FileName = "";
            if (title != null)
            {
                openDlg.Title = title;
            }

            openDlg.CheckFileExists = true;
            openDlg.CheckPathExists = true;

            DialogResult res = openDlg.ShowDialog();
            if (res == DialogResult.OK)
            {
                return openDlg.FileName;
            }

            return null;
        }
        #endregion

        #region GetFolderToOpen 打开的文件夹路径
        /// <summary>
        /// 打开的文件夹路径
        /// </summary>
        /// <param name="newFolderButton">是否显示新建按钮</param>
        /// <returns>返回的路径</returns>
        public static string GetFolderToOpen(bool newFolderButton)
        {
            FolderBrowserDialog folderDialog = new FolderBrowserDialog();
            folderDialog.ShowNewFolderButton = newFolderButton;
            DialogResult res = folderDialog.ShowDialog();
            if (res == DialogResult.OK)
            {
                return folderDialog.SelectedPath;
            }

            return null;
        }
        #endregion

        #region GetPathToSave 得到保存文件的路径
        /// <summary>
        /// 得到保存文件的路径
        /// </summary>
        /// <param name="default_name">默认文件的名称</param>
        /// <param name="title">对话框头</param>
        /// <returns>返回的路径</returns>
        public static string GetPathToSave(string default_name, string title)
        {
            SaveFileDialog saveDlg = new SaveFileDialog();
            saveDlg.Filter = "All Files (*.*)|*.*";
            saveDlg.FileName = default_name;
            saveDlg.OverwritePrompt = false;
            if (title != null)
            {
                saveDlg.Title = title;
            }

            DialogResult res = saveDlg.ShowDialog();
            if (res == DialogResult.OK)
            {
                return saveDlg.FileName;
            }

            return null;
        }
        #endregion

        #region GetFileNameNoPath
        /// <summary>
        /// 取得指定路径的文件名称
        /// </summary>
        /// <param name="fileName_path">指定的路径</param>
        /// <returns>文件名称</returns>
        public static string GetFileNameNoPath(string fileName_path)
        {
            return Path.GetFileName(fileName_path);
        }
        #endregion

        #region GetFileSize
        /// <summary>
        /// 取得指定文件的大小
        /// </summary>
        /// <param name="filePath">指定的文件</param>
        /// <returns>文件的大小</returns>
        public static long GetFileSize(string filePath)
        {
            //FileStream fs = new FileStream(filePath ,FileMode.Open) ;
            //int size = (int)fs.Length ;
            //fs.Close() ;
            if (!File.Exists(filePath))
                return 0;
            FileInfo info = new FileInfo(filePath);
            return info.Length;
        }
        #endregion

        #region ReadFileData 读取指定大小的内容
        /// <summary>
        /// 读取指定大小的内容
        /// </summary>
        /// <param name="fs">打开的文件流</param>
        /// <param name="buff">缓冲区</param>
        /// <param name="count">读取的大小</param>
        /// <param name="offset">偏移量</param>
        public static void ReadFileData(FileStream fs, byte[] buff, int count, int offset)
        {
            int readCount = 0;
            while (readCount < count)
            {
                int read = fs.Read(buff, offset + readCount, count - readCount);
                readCount += read;
            }

            return;
        }
        #endregion

        #region GetFileDir
        /// <summary>
        /// 取得指定文件的目录
        /// </summary>
        /// <param name="fileName_path">文件路径</param>
        /// <returns>目录</returns>
        public static string GetFileDir(string fileName_path)
        {
            return Path.GetDirectoryName(fileName_path);
        }
        #endregion

        #region DeleteFile 删除文件
        /// <summary>
        /// 删除指定的文件
        /// </summary>
        /// <param name="file_path">指定的文件</param>
        /// <param name="extend_name">扩展名</param>
        public static void DeleteFile(string file_path, string extend_name)
        {
            if (Path.GetExtension(file_path) != extend_name)
            {
                file_path += extend_name;
            }

            if (File.Exists(file_path))
            {
                File.Delete(file_path);
            }
        }
        #endregion

        #region EnsureExtendName 确保扩展名正确
        /// <summary>
        /// 确保扩展名正确
        /// </summary>
        /// <param name="origin_path"></param>
        /// <param name="extend_name"></param>
        /// <returns></returns>
        public static string EnsureExtendName(string origin_path, string extend_name)
        {
            if (Path.GetExtension(origin_path) != extend_name)
            {
                origin_path += extend_name;
            }

            return origin_path;
        }
        #endregion

    }
}
